$(document).ready(function(){
	common.body_to_all();
	index_js.bind();
	index_js.init();
	$("#page_title").html("健康日志");
});
var index_js = {};
//初始化
index_js.init = function(){
	var date = common.getUrlParam('date');
	//如果有日期就日期优先
	if(date){
		vm.cur_date = date;
		vm.cur_date_text = date;
	}else{
		vm.cur_date = index_js.get_today();
		vm.cur_date_text = "今天";
	}
	vm.load();
	vm.load_history();
	vm.load_diet();
}
index_js.bind = function(){
	$(window).scroll(function() {
		if(vm.is_right_page_show == false){
			return ;
		}
		var scrollTop = $(this).scrollTop();
		if(scrollTop+$(window).height()>=$(document).height()){
			vm.cur_page++;
			vm.load_history();
		}
	});	
	/**
	 * 监听回退按钮键
	 */
  	window.addEventListener("popstate", function(e) {
  		vm.do_history_change();
  	}, false);		
}
//获取今日的日期，时间格式yyyy-MM-dd
index_js.get_today = function(){
	var today = new Date();
	var year = today.getFullYear();
	//这里少一的
	var month = today.getMonth()+1;
	var date = today.getDate();
	//下面就将每个数字都限制好位数
	return year+"-"+index_js.str(month)+"-"+index_js.str(date);
}
index_js.str = function(str){
	var s = str+"";
	var length = s.length;
	if(length!=2){
		return "0"+s;
	}
	return str;
}
//模拟数据
index_js.obj = {
		project:true,
		food:true,
		food_kg:0,
		breakfast:false,
		breakfast_kg:0,
		lunch:true,
		lunch_kg:0,
		dinner:false,
		dinner_kg:0,
		feed:true,
		feed_kg:0,
		sport:false,
		lose_weight:false,
		person_image:false,
		report:false,
		dietician:true,
		doctor:true,	
}
//历史记录
index_js.history = [
	'2015-8-21','2015-8-20','2015-8-19','2015-8-18','2015-8-17','2015-8-16','2015-8-15','2015-8-20','2015-8-19','2015-8-18','2015-8-17','2015-8-16','2015-8-15','2015-8-20','2015-8-19','2015-8-18','2015-8-17','2015-8-16','2015-8-15',
];
var vm = avalon.define({
	//---------------------------------
	/**
	 * 现在是历史界面
	 */
	$history_back:'history_back',
	/**
	 * 饮食弹框
	 */
	$food_back:'food_back',
	/**
	 * 营养师回复
	 */
	$yinyang_back:'yinyang_back',
	/**
	 * 医生回复
	 */
	$doctor_back:'doctor_back',
	/**
	 * 表示当前的状态，这里要做成一个栈，先进后出
	 */
	$active_back:[],
	/**
	 * 加入到history中
	 */
	push_history:function($state){
		//这里要先判断是否已经有了$state
		var is_have = false;
		$.each(vm.$active_back, function(index) {    
			if(vm.$active_back[index] == $state){
				is_have = true;
			}
		});
		if(is_have == false){
			vm.$active_back.push($state);
			//这里要判断是否有日期
			var date = common.getUrlParam('date');
		  	var state = {
		  		title: $state,
		  		url: "#"+$state,
		  	};
		  	//对日期参数进行保留
		  	if(date){
		  		state.url = "?date="+date+"#"+$state;
		  	}
		 	window.history.pushState(state, state.title, state.url);
		}
	},
	/**
	 * 当history改变时执行的回调方法
	 */
	do_history_change:function(){
		if(!vm.$active_back.length){
			return ;
		}
		//获取最新进来的值
		switch (vm.$active_back[vm.$active_back.length-1]){
			case vm.$history_back:
				//显示左边页面
				vm.change_to_left_page();
				break;
				
			case vm.$food_back:
				vm.is_show_food_modal = false;
				vm.is_show_reply_modal = false;
				break;
				
			case vm.$yinyang_back:
				vm.is_show_food_modal = false;
				vm.is_show_reply_modal = false;			
				break;
				
			case vm.$doctor_back:
				vm.is_show_food_modal = false;
				vm.is_show_reply_modal = false;			
				break;			
				
			default:
				//什么都不做
				break;
		}
		if(vm.$active_back.length){
			vm.$active_back.pop();
		}
	},
	//返回
	go_history:function(){
		if(vm.$active_back.length){
			history.go(-1);
			vm.$active_back.pop();
		}		
	},
	//---------------------------------		
	//标记是否显示遮罩
	is_mask_show:false,	
	$id:"main_controller",
	//是否左边页面显示
	is_left_page_show:true,
	//是否右边页面显示
	is_right_page_show:false,
	//展示左边页面
	change_to_left_page:function(is_back){
		vm.is_left_page_show = true;
		vm.is_right_page_show = false;
		if(is_back){
			vm.go_history();
		}
	},
	//展示右边页面
	change_to_right_page:function(){
		vm.is_left_page_show = false;
		vm.is_right_page_show = true;		
		vm.push_history(vm.$history_back);
	},
	//这个对象判断当前时间上下文的各个项目的填写状态
	// true 已填写 false未填写
	obj:{
		//干预项目
		project:false,
		//运动
		sport:false,
		//减重感受
		lose_weight:false,
		//上传个人照片
		person_image:false,
		//上传体检报告
		report:false,
		//营养师回复
		dietician:false,
		//医生回复
		doctor:false,
	},
	//为了动态修改图片所以要avalon来托管
	images:{
		project_img:img_pix+'log-project-done.png',
		food_img:img_pix+'log-food-done.png',
		breakfast_img:img_pix+'fork-done.png',
		lunch_img:img_pix+'fork-done.png',
		dinner_img:img_pix+'fork-done.png',
		feed_img:img_pix+'fork-done.png',
		sport_img:img_pix+'log-sport-done.png',
		lose_weight_img:img_pix+'log-heart-done.png',
		person_image_img:img_pix+'log-image-done.png',
		report_img:img_pix+'log-report-done.png',
		dietician_img:img_pix+'log-huifu-done.png',		
		doctor_img:img_pix+'log-huifu-done.png',		
	},
	//今天的时间
	today_date:index_js.get_today(),
	//当前的时间上下文
	cur_date:'',
	//这个只是用来展示标题的
	cur_date_text:'',
	//历史记录数组
	history:[
		
	],
	//营养师或医生的回复
	reply:'今日暂无回复',
	//根据时间上下文来加载状态
	load:function(){
		vm.is_mask_show = true;
		$.ajax({
			type:"post",
			url:get_log_status_url,
			error:function(){
				vm.is_mask_show = false;
				vm.toast_msg = "网络错误";
				vm.is_toast_show = true;
				vm.clear_toast();						
			},
			data:"date="+vm.cur_date,
			dataType:"json",
			success:function(data){
				vm.is_mask_show = false;
				console.log(data);
				vm.obj = data;
				//根据是否填写的值来进行图片状态的切换
				for(var p in vm.obj){
					if(vm.obj[p] === false){
						if(vm.images[p+'_img']){
							if(vm.images[p+'_img'].indexOf("-done")==-1){
								vm.images[p+'_img'] = (vm.images[p+'_img'].split('.png')[0]+"-done.png");	
							}					
						}				
					}else{
						if(vm.images[p+'_img']){
							if(vm.images[p+'_img'].indexOf("-done")!=-1){
								vm.images[p+'_img'] = (vm.images[p+'_img'].split('-done')[0]+".png");	
							}					
						}
					}
				}				
			},
		});
	},
	//当前页
	cur_page:1,
	//是否正在加载数据，主要用于滚动加载
	is_loading:false,	
	//是否第一次加载
	is_first_loading:true,
	//加载历史记录，这里顺序查询出来前端容易处理
	load_history:function(callback){
		if(vm.is_loading==true){
			return ;
		}
		vm.is_loading = true;		
		$.ajax({
			type:"post",
			url:get_history_log_url,
			dataType:"json",
			data:"cur_page="+vm.cur_page,
			success:function(data){
				vm.is_loading = false;
				//判断是否拥有今天的记录
				var is_have_today = false;
				var list = data;
				for(var i=0;i<list.length;i++){
					if(list[i].datetime==vm.cur_date){
						is_have_today = true;
						break;
					}
				}
				if(is_have_today==false && vm.is_first_loading == true){
					list.push({
						datetime:vm.cur_date
					});
				}
				var length = list.length;
				var result = [];
				//这里是倒序的
				for(var i=0;i<length;i++){
					//根据排序，现在是直接判断是不是今天
					if(list[i].datetime==vm.today_date && vm.is_first_loading == true){
						result.push({
							show_value:list[i].datetime+"（今天）",
							value:list[i].datetime,
						});				
					}else{
						result.push({
							show_value:list[i].datetime,
							value:list[i].datetime,
						});					
					}
				}				
				vm.history.pushArray(result);	
				if(!data || data.length<=0){
					//这里重新处理页数
					if(vm.cur_page!=1){
						vm.cur_page--;
					}
					vm.toast_msg = "没有更多数据了";
					vm.is_toast_show = true;
					vm.clear_toast();
				}	
				vm.is_first_loading = false;
				if(callback){
					callback();
				}
			},
			error:function(){
				vm.is_loading = false;
				vm.toast_msg = "网络错误";
				vm.is_toast_show = true;
				vm.clear_toast();						
			}
		});
	},
	//重新加载某个日期的数据
	active_date:function(index){
		//如果是点击到现在的时间点就直接切换视图就可以了
		var time = vm.history[index].value;
		//点击当前时间上下文
		if(time != vm.cur_date){
			vm.load();
		}
		//这里追加判断是否是今天
		if (time == vm.today_date) {
			vm.cur_date_text = "今天";
		} else {
			vm.cur_date_text = time;
		}	
		vm.change_to_left_page();
		vm.go_history();
		vm.cur_date = time;
		//避免无法执行的情况
		setTimeout(function(){
			window.history.pushState({
			  	title: "title",
			  	url: "?date="+time			
			}, "title", "?date="+time);			
		},500);
		vm.load();
		vm.load_diet();
	},
	//加载营养师回复
	load_dietician_reply:function(callback){
		vm.reply = '正在加载...<i class="fa fa-spinner fa-spin fa-fw"></i>';
		$.ajax({
			type:"post",
			url:get_diaryreply_url,
			data:'date='+vm.cur_date,
			dataType:'json',
			success:function(data){
				if(!data){
					vm.reply = "今天没有回复"
				}else{
					vm.reply = data;
				}
				if(callback){
					callback();
				}				
			},
			error:function(){
				vm.toast_msg = "网络错误";
				vm.is_toast_show = true;
				vm.clear_toast();						
			}
		});

	},
	//加载医生回复
	load_doctor_reply:function(callback){
		vm.reply = '正在加载...<i class="fa fa-spinner fa-spin fa-fw"></i>';
		$.ajax({
			type:"post",
			url:get_doctreply_url,
			data:'date='+vm.cur_date,
			dataType:'json',
			success:function(data){
				if(!data){
					vm.reply = "今天没有回复"
				}else{
					vm.reply = data;
				}
				if(callback){
					callback();
				}				
			},
			error:function(){
				vm.toast_msg = "网络错误";
				vm.is_toast_show = true;
				vm.clear_toast();						
			}
		});
	},
	//下面基本上都是点击事件，基本都将当前的时间上下文作为参数传到另一个页面
	go_to_project:function(){
		location.href = project_url+"?date="+vm.cur_date;
	},
	go_to_sport:function(){
		location.href = sport_url+"?date="+vm.cur_date;
	},
	go_to_weight:function(){
		location.href = lose_weight_url+"?date="+vm.cur_date;
	},
	go_to_person_image:function(){
		location.href = person_image_url+"?date="+vm.cur_date;
	},
	go_to_report:function(){
		location.href = report_url+"?date="+vm.cur_date;
	},	
	//标记是否显示饮食模态框
	is_show_food_modal:false,
	//关闭饮食模态框
	close_food_modal:function(){
		vm.is_show_food_modal = false;
		vm.go_history();
	},
	//打开饮食模态框
	open_food_modal:function(){
		vm.is_show_food_modal = true;
		vm.push_history(vm.$food_back);
	},
	//标记是否显示回复模态框
	is_show_reply_modal:false,
	//关闭回复模态框
	close_reply_modal:function(){
		vm.is_show_reply_modal = false;
		vm.go_history();
	},
	//打开医生模态框
	open_reply_modal_1:function(){
		vm.is_show_reply_modal = true;	
		vm.load_doctor_reply(function(){
			
		});
		vm.push_history(vm.$doctor_back);
	},	
	//打开营养师模态框
	open_reply_modal_2:function(){
		vm.is_show_reply_modal = true;	
		vm.load_dietician_reply(function(){
			
		});
		vm.push_history(vm.$yinyang_back);
	},	
	//标记是否正在加载餐类型
	is_load_diet:false,
	//餐类型
	diet_list:[],
	//加载所有的餐类型
	load_diet:function(){
		vm.is_load_diet = true;
		//get_diet_url
		$.ajax({
			type:"post",
			url:get_diet_url,
			dataType:'json',
			data:"date="+vm.cur_date,
			success:function(data){
				vm.is_load_diet = false;
				var all_kg = 0; 
				for(var i=0;i<data.length;i++){
					if(!data[i].value){
						data[i].value = 0;
					}		
					all_kg += new Number(data[i].value);
				}
				vm.diet_list = data;
				vm.all_kg = all_kg;
			},
			error:function(){
				vm.is_load_diet = false;
				vm.toast_msg = "网络错误";
				vm.is_toast_show = true;
				vm.clear_toast();						
			}
		});		
	},
	//所有的总量
	all_kg:0,
	//跳转到餐饮那边
	go_to_diet:function(index){
		//food_submit_url
		var obj  = vm.diet_list[index];
		vm.close_food_modal();
		setTimeout(function(){
			//跳转到已提交页面
			if(obj.status === true){
				location.href =food_submit_url+'?date='+vm.cur_date+'&dictlibraryid='+obj.dictlibraryid+"&name="+encodeURI(encodeURI(obj.libraryname));
			}else{
				location.href =food_url+'?date='+vm.cur_date+'&dictlibraryid='+obj.dictlibraryid;
			}			
		},100);
	},
	//----------------
	//toast的信息
	toast_msg:'',
	//是否要展示toast
	is_toast_show:false,
	//定时器
	$timeout:0,
	//消息隐藏
	clear_toast:function(){
		//设置定时器
		if(vm.$timeout){
			clearTimeout(vm.$timeout);
		}
		vm.$timeout = setTimeout(function(){
			vm.is_toast_show = false;
			vm.toast_msg = '';
		},3000);		
	},	
	//-----------------		
});
avalon.scan();
avalon.ready(function(){
	$('body').css('opacity',1);
});
